﻿define(function () {
    function analyticContext(text) {
        let obj = {};
        let arr = text.split("\n").map(item => item.trim()).filter(item => item);
        arr.forEach(exp => {
            let temp = exp.split(":");
            let expressions = temp[0].trim().split('[').map((value) => value.replace(']', ''));
            let value = temp[1].trim();
            var result = analyticExpression(expressions, value);
            copy(obj, result);
        });

        return obj;
    }

    function copy(target, source) {
        for (var key in source) {
            if (target[key] != undefined) {
                if (source[key] instanceof String ||
                    source[key] instanceof Number ||
                    source[key] instanceof Date ||
                    source[key] instanceof Boolean)
                    target[key] = source[key];
                else
                    copy(target[key], source[key]);
            }
            else
                target[key] = source[key];
        }
    }

    function analyticExpression(expArray, value) {
        if (expArray.length > 0) {
            let obj;
            var key = expArray[0]
            var numberKey = Number.parseInt(key);
            var result = analyticExpression(expArray.slice(1), value);
            if (isNaN(numberKey)) {
                obj = {};
                obj[key] = result;
            } else {
                obj = [];
                obj[numberKey] = result;
            }

            return obj;
        }
        return value;
    }

    return {
        analyticContext: analyticContext
    };
});

